import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { RicheditorComponent } from 'src/app/embed/richeditor/richeditor.component';
import { BoardCollectBoardGroupVo } from 'src/app/model/board-collect-board-group-vo';
import { BoardGroupVo } from 'src/app/model/board-group-vo';
import { BoardVo } from 'src/app/model/board-vo';
import { MemberVo } from 'src/app/model/member-vo';
import { ThreadsCategoryVo } from 'src/app/model/threads-category-vo';
import { ThreadsVo } from 'src/app/model/threads-vo';
import { BoardGroupService } from 'src/app/services/board-group.service';
import { BoardService } from 'src/app/services/board.service';
import { BtnNaviSharedService } from 'src/app/services/btn-navi-shared.service';
import { MemberStorageService } from 'src/app/services/member-storage.service';
import { ThreadsService } from 'src/app/services/threads.service';
import { UtilService } from 'src/app/services/util.service';

@Component({
  selector: 'app-publish-threads',
  templateUrl: './publish-threads.component.html',
  styles: [``]
})
export class PublishThreadsComponent implements OnInit {
  public topic: any = {
    category: 0,
    title: '',
    content: '',
    volumes: 0,
    board: 0,
    token: '',
    ip: '127.0.0.1'
  };
  //当前登录的会员
  private curMember: MemberVo | null;
  //版块select
  public boardResult: BoardVo[] = [];
  //版块组select
  public boardGroupResult: BoardGroupVo[] = [];
  //话题类型
  public categories: ThreadsCategoryVo[] = [];
  //编辑器:AngularEditor
  @ViewChild('editor', { static: false })
  public richEditorCmp!: RicheditorComponent;
  //发布操作结果的消息
  public errorMessage: string = '';

  constructor(
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private threadsService: ThreadsService,
    private boardService: BoardService,
    private boardGroupService: BoardGroupService,
    private memberStorage: MemberStorageService,
    private btnNaviSharedService: BtnNaviSharedService,
    private util: UtilService) {
    this.btnNaviSharedService.active(true);//需要全局的导航
    this.topic.token = this.util.randomAlphaNumeric(6) || '123456';
    this.curMember = this.memberStorage.get();
    this.memberStorage.getIpCliente().subscribe(ipAddr=>this.topic.ip=ipAddr);
  }

  ngOnInit(): void {
    if(null === this.curMember ){
      this.router.navigate(['/member/login']);
      return;
    }
    this.activatedRoute.queryParams.subscribe(params => {
      //将选中版块设为:ref的版块ID
      this.topic.board = parseInt(params['board'] || '0');
      //将选中版块组设为:ref的版块组ID
      this.topic.volumes = parseInt(params['volumes'] || '0');
      this.fillCascadeSelect(this.topic.board, this.topic.volumes);
    });
  }
  //填充话题类型
  private fillCategorySelect(boardId: number, boardGroupId: number): void {
    if (boardId <= 0 || boardGroupId <= 0) {
      return;
    }
    this.threadsService.getPublishCategory(boardGroupId, boardId).subscribe({
      next: response => {
        //更新话题类型列表
        this.categories = response;
        //将选中版块设为数组的第一个元素
        this.topic.category = this.categories[0].id;
      },
      error: err => {
        console.error('[PublishThreads-CTL]form query category Error: ' + err.error);
      },
      complete: () => {
        console.log('[PublishThreads-CTL]form query category Completed');
      }
    });
  }
  //填充版块组和版块的select
  private fillCascadeSelect(boardId: number, boardGroupId: number): void {
    //总是取得所有版块组
    this.queryBoardGroups();
    //若版块可用 && 版块组可用
    if (boardId>0 && boardGroupId>0) {
      //查询版块组下的所有可用的版块
      this.boardService.getAllUsed(boardGroupId).subscribe({
        next: response => {
          //填充版块列表
          this.boardResult = response;
        },
        error: err => {
          //this.errorMessage = err.error; 
          console.error('[PublishThreads-CTL]form fill Error: ' + err.error);
        },
        complete: () => {
          console.log('[PublishThreads-CTL]form fill Completed');
          this.fillCategorySelect(boardId, boardGroupId);
        }
      });
    }
  }

  //查询所有可用的版块组
  public queryBoardGroups(): void {
    this.boardGroupService.getAllUsed().subscribe({
      next: response => {
        //更新版块组列表
        this.boardGroupResult = response;
      },
      error: err => {
        console.error('[PublishThreads-CTL]query all boardGroup Error: ' + err.error);
      },
      complete: () => {
        console.log('[PublishThreads-CTL]query all boardGroup Completed');
      }
    });
  }

  //改变版块组后更新版块列表
  public changeBoardGroup(event: Event): void {
    this.boardService.getAllUsed(this.topic.volumes).subscribe({
      next: response => {
        //更新版块列表
        this.boardResult = response;
        //将选中版块设为数组的第一个元素
        this.topic.board = this.boardResult[0].id;
      },
      error: err => {
        console.error('[PublishThreads-CTL]query board by boardGroup Error: ' + err.error);
      },
      complete: () => {
        console.log('[PublishThreads-CTL]query board by boardGroup Completed');
      }
    });
  }

  //检查版块的状态是否可以发布话题
  private checkBoardStatus(boardId:number): boolean{
    if(boardId <= 0){
      return false;
    }
    return this.boardResult.some((ele:BoardVo)=>ele.id === boardId && ele.status === 4);
  }

  //发布话题
  public publish(submitBtn: HTMLButtonElement): void {
    submitBtn.disabled = true;
    submitBtn.setAttribute('value', '...');
    if (this.curMember === null) {
      this.util.alertError('暂不支持游客发布话题');
      return;
    }
    if(!this.checkBoardStatus(this.topic.board)){
      return this.util.alertError('版块暂时禁止发布话题');
    }
    //
    this.threadsService.publish(
      this.topic.volumes,
      this.topic.board,
      this.topic.category,
      this.topic.title,
      this.richEditorCmp.getContent(),
      this.curMember?.id ?? 0,
      this.curMember?.nickname ?? 'guest',
      this.topic.token,
      this.topic.ip).subscribe({
        next: response => {
          let threadsVal: ThreadsVo = response;
          //跳转到回复的内容页
          this.router.navigate([threadsVal.link]);
        },
        error: err => {
          if (err instanceof HttpErrorResponse) {
            if (err.error instanceof ErrorEvent) {
              this.errorMessage = err.error.message;
            } else {
              this.errorMessage = (err.status === 404) ? '发布操作失败' : err.error;
            }
          } else if (err instanceof Error) {
            this.errorMessage = err.message;
          } else { this.errorMessage = err; }
          //
          submitBtn.disabled = false;
          submitBtn.setAttribute('value', '发布');
        },
        complete: () => {
          console.log('[PublishThreads-CTL]publish action Completed');
        }
      });
  }
}
